#include <lilv/lilv.h>
#include "LV2Unit.h"

/*=== lilv_world ===*/
inline LilvWorld* lilv_world_new_wrapper()
{
   DEBUG("Lilv world create\n");
   return lilv_world_new();
}
LilvWorld* get_lilv_world()
{
   static LilvWorld *world = lilv_world_new_wrapper();
   if (world == NULL)
      textException("Cannot initialize Lilv library: cannot create world\n");
   return world;
}

LV2Unit::LV2Unit()
{
}

void LV2Unit::ar(unsigned port, sample_t *buffer, jack_nframes_t len, Options options)
{
}

void LV2Unit::load(string fileName)
{
   LilvWorld *world = get_lilv_world();

   /* Load a plugin */
   LilvNode *uri = lilv_new_uri(world, fileName.c_str());
   if (uri == NULL)
   {
      DEBUG("Invalid URI: %s\n", fileName.c_str());
      textException("Invalid URI specified (%s)", fileName.c_str());
   }
   int rc = lilv_world_load_resource(world, uri);
   if (rc == -1)
      textException("Error loading LV2 resource\n");

   DEBUG("lilv_world_load_resource --> %d\n", rc);
   
   /* Find the plugin in the world */
   const LilvPlugins *plugins = lilv_world_get_all_plugins(world);
   DEBUG("There are %d plugins in the collection\n", lilv_plugins_size(plugins));
   const LilvPlugin  *plugin  = lilv_plugins_get_by_uri(plugins, uri);
   if (plugin == NULL)
   {
      DEBUG("The required plugin can not be found in the world\n");
      textException("Can not load plugin");
   }

   /* Verify the plugin */
   DEBUG(
         lilv_plugin_verify(plugin)
         ? "Plugin is verified to be correct\n"
         : "Plugin is not correct\n");

   /* Some useful data */
   DEBUG("The plugin has %d ports\n", lilv_plugin_get_num_ports(plugin));

   /* Ports */
   for (uint32_t i = 0; i < lilv_plugin_get_num_ports(plugin); i ++)
   {
      const LilvPort *port = lilv_plugin_get_port_by_index(plugin, i);
      LilvNode *name = lilv_port_get_name(plugin, port);
      DEBUG("%u: %s\n", i, lilv_node_as_string(name));
   }

   lilv_node_free(uri);
}
